package com.greatchn.authorization_server.handler;

import com.greatchn.authorization_server.util.ServiceAssert;
import com.greatchn.authorization_server.web.po.OauthUserInfo;
import com.greatchn.authorization_server.web.srv.OauthUserInfoSrv;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @UserDetailsHandler: 用户详情处理
 * @author: ZBoHang
 * @time: 2023/2/28 10:34
 */
@Component("userDetailsHandler")
public class UserDetailsHandler implements UserDetailsService {

    @Resource
    private OauthUserInfoSrv oauthUserInfoSrv;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        OauthUserInfo userInfo = this.oauthUserInfoSrv.getByUserName(username);
        ServiceAssert.notNull(userInfo, "用户不存在!");
        Set<String> roleNameSet = this.oauthUserInfoSrv.getRoleNameByUserName(username);
        // 包装用户
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>(12);

        for (String role : roleNameSet) {
            grantedAuthorities.add(new SimpleGrantedAuthority(role));
        }

        return new User(username, userInfo.getPassword(), grantedAuthorities);
    }
}
